package com.example.userservice.common;

import com.example.userservice.exception.IllegalParamsException;
import com.example.userservice.exception.WithTypeException;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.lang3.reflect.FieldUtils;

/**
 * @author ：Anitaxiaofeng
 * @description：
 * @create 2018-06-05
 **/
public class Exception2CodeRepo {

    private static final ImmutableMap<Object,RestCode> MAP = ImmutableMap.<Object, RestCode>builder()
            .put(IllegalParamsException.Type.WRONG_PAGE_NUM,RestCode.WRONG_PAGE)
            .build();

    public static RestCode getCode(Throwable throwable) {
        if(throwable == null) {
            return RestCode.UNKNOWN_ERROR;
        }
        Object target = throwable;
        if(throwable instanceof WithTypeException) {
            Object type = getType(throwable);
            if (type != null) {
                target = type;
            }
        }
            RestCode restCode = MAP.get(target);
            if(restCode!=null) {
                return restCode;
            }
            Throwable rootCause = ExceptionUtils.getRootCause(throwable);
            if(rootCause!=null) {
                return getCode(rootCause);
            }
            return RestCode.UNKNOWN_ERROR;
        }


    private static Object getType(Throwable throwable) {
        try{
          return FieldUtils.readDeclaredField(throwable,"type",true);
        } catch (Exception e) {
            return null;
        }
    }
}



